<template>
  <view class="user-manage-container">
    <!-- 用户列表 -->
    <view class="user-list">
      <view
        class="user-item"
        v-for="(item, index) in userList"
        :key="item._id"
        @click="handleEditUser(item)"
      >
        <view class="user-info">
          <view class="username">{{ item.username }}</view>
          <view class="info-row">
            <view class="user-type">
              {{ item.user_type === "root" ? "管理员" : "普通用户" }}
            </view>
            <view class="password">密码：{{ item.password }}</view>
          </view>
        </view>
        <view class="operation" @click.stop>
          <uv-switch
            v-model="item.status"
            :loading="item.loading"
            :active-value="1"
            :inactive-value="0"
            @change="(value) => handleStatusChange(value, item, index)"
          ></uv-switch>
          <uv-button
            type="error"
            size="mini"
            text="删除"
            @click="handleDelete(item)"
            v-if="item.username !== 'root'"
          ></uv-button>
        </view>
      </view>
    </view>

    <!-- 分页加载 -->
    <view class="pagination">
      <uv-loadmore
        :status="loadMoreStatus"
        @loadmore="loadMore"
        :icon-size="17"
        :load-text="{
          loadmore: '点击或上拉加载更多',
          loading: '正在加载...',
          nomore: '没有更多了',
        }"
      />
    </view>

    <!-- 编辑弹窗 -->
    <uv-popup ref="popup" @change="popupChange">
      <view class="edit-popup">
        <view class="popup-header">
          <text class="title">编辑用户信息</text>
          <uv-icon name="close" size="20" @click="closeEditPopup"></uv-icon>
        </view>
        <view class="popup-content">
          <uv-form
            :model="editForm"
            ref="editFormRef"
            labelPosition="top"
            labelWidth="200"
          >
            <uv-form-item label="用户名" prop="username" borderBottom>
              <uv-input
                v-model="editForm.username"
                placeholder="请输入用户名"
                :disabled="currentEditUser?.username === 'root'"
                :customStyle="{ padding: '16rpx 0' }"
              />
            </uv-form-item>
            <uv-form-item label="新密码" prop="password" borderBottom>
              <uv-input
                v-model="editForm.password"
                type="password"
                placeholder="不修改请留空"
                :customStyle="{ padding: '16rpx 0' }"
              />
            </uv-form-item>
          </uv-form>
        </view>
        <view class="popup-footer">
          <view class="footer-btn">
            <uv-button type="info" text="取消" @click="closeEditPopup" />
          </view>
          <uv-button type="primary" text="确定" @click="handleUpdateUser" />
        </view>
      </view>
    </uv-popup>
  </view>
</template>
<script setup>
import { ref, onMounted } from "vue";
import cloudConfig from "@/config/uniCloudConfig.js";
const userList = ref([]);
const pageSize = 10;
const currentPage = ref(1);
const loadMoreStatus = ref("loadmore");
const hasMore = ref(true);
const currentEditUser = ref(null);
const editForm = ref({
  username: "",
  password: "",
  user_type: "normal",
});
const popup = ref(null);

const uniCloudUsersManager = cloudConfig.getCloudObject("usersManager");
// 获取用户列表
const getUserList = async (page = 1, append = false) => {
  try {
    const res = await uniCloudUsersManager.getUserList({
      page,
      pageSize,
    });

    if (res.code === 0) {
      if (append) {
        userList.value = [...userList.value, ...res.data.list];
      } else {
        userList.value = res.data.list;
      }
      hasMore.value = res.data.total > userList.value.length;
      loadMoreStatus.value = hasMore.value ? "loadmore" : "nomore";
    }
  } catch (error) {
    console.error(error);
    loadMoreStatus.value = "loadmore";
  }
};

// 更新用户信息
const updateUser = async (userId, updateData) => {
  try {
    let newData = {
      ...updateData,
    };
    Reflect.deleteProperty(newData, "_id");
    const res = await uniCloudUsersManager.updateUser(userId, newData);

    if (res.code === 0) {
      uni.showToast({
        title: "更新成功",
        icon: "success",
      });
      return true;
    } else {
      uni.showToast({
        title: res.message || "更新失败",
        icon: "none",
      });
      return false;
    }
  } catch (error) {
    console.error("更新用户信息失败:", error);
    uni.showToast({
      title: "更新失败，请重试",
      icon: "none",
    });
    return false;
  }
};

// 处理状态变更
const handleStatusChange = async (value, item, index) => {
  if (item.username === "root") {
    uni.showToast({
      title: "不能修改超级管理员状态",
      icon: "none",
    });
    userList.value[index].status = 1;
    return;
  }

  userList.value[index].loading = true;
  const success = await updateUser(item._id, {
    status: value ? 1 : 0,
  });

  if (!success) {
    userList.value[index].status = !value;
  }
  userList.value[index].loading = false;
};

// 打开编辑弹窗
const handleEditUser = (item) => {
  if (!item) return;
  currentEditUser.value = item;
  editForm.value = {
    username: item.username,
    password: "",
    user_type: item.user_type,
  };
  popup.value.open("center");
};

// 关闭编辑弹窗
const closeEditPopup = () => {
  popup.value.close();
  currentEditUser.value = null;
  editForm.value = {
    username: "",
    password: "",
    user_type: "normal",
  };
};

// 弹窗状态改变回调
const popupChange = (e) => {
  console.log("弹窗状态改变：", e);
};

// 提交更新
const handleUpdateUser = async () => {
  if (!currentEditUser.value) return;

  const updateData = {
    username: editForm.value.username,
    user_type: editForm.value.user_type,
  };

  if (editForm.value.password) {
    updateData.password = editForm.value.password;
  }

  const success = await updateUser(currentEditUser.value._id, updateData);
  if (success) {
    const index = userList.value.findIndex(
      (item) => item._id === currentEditUser.value._id
    );
    if (index !== -1) {
      userList.value[index] = {
        ...userList.value[index],
        ...updateData,
      };
    }
    closeEditPopup();
  }
};

// 删除用户
const handleDelete = (item) => {
  if (item.username === "root") return;

  uni.showModal({
    title: "提示",
    content: "确定要删除该用户吗？",
    success: async (res) => {
      if (res.confirm) {
        try {
          const res = await uniCloudUsersManager.deleteUser({
            _id: item._id,
          });
          if (res.code === 0) {
            uni.showToast({
              title: "删除成功",
              icon: "success",
            });
            resetAndReload();
          } else {
            uni.showToast({
              title: res.message,
              icon: "none",
            });
          }
        } catch (error) {
          console.error(error);
        }
      }
    },
  });
};

// 加载更多
const loadMore = async () => {
  if (!hasMore.value || loadMoreStatus.value === "loading") return;
  loadMoreStatus.value = "loading";
  currentPage.value += 1;
  await getUserList(currentPage.value, true);
};

// 重置并重新加载
const resetAndReload = () => {
  currentPage.value = 1;
  hasMore.value = true;
  loadMoreStatus.value = "loadmore";
  getUserList(1);
};

onMounted(() => {
  getUserList(1);
});
</script>

<style lang="scss" scoped>
.user-manage-container {
  padding: 20rpx;
  min-height: 100vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;

  .user-list {
    flex: 1;

    .user-item {
      background-color: #fff;
      border-radius: 12rpx;
      padding: 30rpx;
      margin-bottom: 20rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .user-info {
        .username {
          font-size: 32rpx;
          color: #333;
          margin-bottom: 10rpx;
        }

        .info-row {
          display: flex;
          align-items: center;
          gap: 20rpx;

          .user-type {
            font-size: 24rpx;
            color: #666;
          }

          .password {
            font-size: 24rpx;
            color: #666;
          }
        }
      }

      .operation {
        display: flex;
        align-items: center;
        gap: 20rpx;
      }
    }
  }

  .pagination {
    padding: 20rpx 0;
  }
}

.edit-popup {
  width: 600rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  height: calc(100% - 40rpx);
  position: relative;

  .popup-header {
    display: flex;
    justify-content: space-between !important;
    margin-bottom: 20rpx;
  }

  .popup-content {
    padding: 10rpx 0;
  }

  .popup-footer {
    margin-top: 20rpx;
    border-top: 1px solid #eee;
    display: flex;
    justify-content: flex-end;
    position: absolute;
    bottom: 26rpx;
    right: 10rpx;

    .footer-btn {
      margin-right: 20rpx;
    }
  }
}
</style>
